import qs from 'qs';

export default {
	get(url, params) {
		if (params && Object.keys(params).length !== 0) {
		    url += '?' + qs.stringify(params);
		}
		return this.request({
			url: url,
			method: 'GET',
			data: {},
			header: {}
		});
	},
	post(url, params) {
		params = params && qs.stringify(params);
		return this.request({
			url: url,
			method: 'POST',
			data: params,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			}
		});
	},
	upload(url, filePath) {
		return new Promise((resolve, reject)=>{
			uni.uploadFile({
				url: 'http://api.horse.com' + url,
				filePath: filePath,
				name: 'xupload',
				success: (res)=>{
					console.log(res.data);
					resolve(JSON.parse(res.data));
				},
				fail: (err)=>{
					console.log(err);
					reject(err);
				}
			});
		});	
	},
	request(opts) {
		opts.url = 'http://api.horse.com' + opts.url;
		console.log('request url:' + opts.url);
		console.log('request data:' + JSON.stringify(opts.data));
		
		// 获取token，封装到请求头中
		try {
			const token = uni.getStorageSync('token');
			Object.assign(opts.header, {
				'Token': token
			});
		} catch(e) {} 
		
		return new Promise((resolve, reject)=>{
			uni.request({
				url: opts.url,
				method: opts.method,
				data: opts.data,
				header: opts.header,
				success: (res)=>{
					console.log(res.data);
					resolve(res.data);
				},
				fail: (err)=>{
					console.log(err);
					reject(err);
				}
			});
		});	
	}
}